/*
 * @Auther        : SR
 * @Date          : 2022-02-25 08:42:00
 * @LastEditTime  : 2022-02-28 17:23:04
 */
package windows

import (
	"fmt"
	"ipfs-browser/src/IPFS"
	"ipfs-browser/src/Metadata"
	"ipfs-browser/src/es7"
	"log"
	"path/filepath"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
)

/*
uploadScreen select file and upload

VScroll(HBox(路径，搜索类型，搜索Button),提示信息)
*/
func uploadScreen(win fyne.Window) fyne.CanvasObject {
	formStruct := struct {
		Name        string
		Description string
	}{
		Name:        "file name",
		Description: "description",
	}

	filePath := widget.NewLabel("file path")
	selectBar := widget.NewSelect([]string{"text", "picture", "video"}, func(s string) { fmt.Println("selected", s) })

	fileInfo := widget.NewLabel("file Info") //搜索栏下方的显示信息

	// 上传时添加信息

	formData := binding.BindStruct(&formStruct)
	form := newFormWithData(formData)
	form.OnSubmit = func() {
		log.Println("upload with",
			"\nfile path :", filePath.Text,
			"\nfile name :", formStruct.Name,
			"\nfile Description :", formStruct.Description,
			"\nfile cid :", "input cid here",
			"\nfile type :", selectBar.Selected,
			"\nTimestamp :", "input timestamp here",
		)
		// log.Println("Struct:\n", formStruct)
		cid, err := IPFS.Upload(filePath.Text)
		if err != nil {
			log.Println(err.Error())
			panic(err)
		}
		mt := Metadata.Metadata{
			Name:        formStruct.Name,
			Description: formStruct.Description,
			CID:         cid,
			Filetype:    selectBar.Selected,
			Timestamp:   time.Now(),
		}
		msg, err1 := es7.AddDocument(selectBar.Selected, mt)
		if err1 != nil {
			log.Println(err1.Error())
			panic(err1)
		}
		log.Println(msg)
	}

	openButton := widget.NewButton("File Select", func() {
		fd := dialog.NewFileOpen(func(reader fyne.URIReadCloser, err error) {
			if err != nil {
				dialog.ShowError(err, win)
				return
			}
			if reader == nil {
				log.Println("Cancelled")
				return
			}

			//! filePathOpened(reader)
			log.Println("select path:", reader.URI().Path())
			filePath.SetText(reader.URI().Path())
			fileInfo.SetText("file name:" + reader.URI().Name())
			formStruct.Name = reader.URI().Name()
			fmt.Println(form.Items[0].Widget)
			// form.CreateRenderer().Refresh()
		}, win)
		// fd.SetFilter(storage.NewExtensionFileFilter([]string{".png", ".jpg", ".jpeg"}))
		fd.Show()
	})

	// uploadButton := widget.NewButton("upload", func() {
	// 	log.Println("upload file " + fileInfo.Text +
	// 		"; file path: " + filePath.Text)
	// })

	return container.NewBorder(
		container.NewBorder(
			nil, nil, nil,
			container.NewHBox(
				widget.NewSeparator(), //添加filePath的边界
				openButton,
				selectBar,
				// uploadButton,
			),
			container.NewHScroll(filePath),
		), nil, nil, nil,
		container.NewVBox(widget.NewSeparator(), form),
	)
}
func getFileName(path string) (fileName string) {
	return filepath.Base(path)
}
